﻿using System;
using System.Xml;

namespace Graphe
{
    public class DocumentGroupCollection : System.Collections.ObjectModel.ObservableCollection<DocumentGroup>
    {
        public void Load(string path)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path);

            path = path.Replace("Index.xml", String.Empty);

            foreach (XmlNode node in doc.DocumentElement.ChildNodes)
            {
                if (node.Name == "Group")
                {
                    DocumentGroup group = CreateGroup(node, path);
                    Add(group);
                }
            }
        }

        public DocumentGroup CreateGroup(XmlNode groupNode, string path)
        {
            DocumentGroup group = new DocumentGroup();
            group.Name = groupNode.Attributes["Name"].Value;

            foreach (XmlNode node in groupNode.ChildNodes)
            {
                if (node.Name == "Manuscript")
                {
                    if (group.Manuscripts == null)
                        group.Manuscripts = new DocumentCollection();
                    
                    Document manuscript = new Document();
                    manuscript.Name = node.Attributes["Name"].Value;
                    manuscript.IndexFileName = node.InnerText;
                    manuscript.Load(path);

                    group.Manuscripts.Add(manuscript);
                }
                else if (node.Name == "Group")
                {
                    if (group.Groups == null)
                        group.Groups = new DocumentGroupCollection();

                    group.Groups.Add(CreateGroup(node, path));
                }
            }

            return group;
        }

        public Document FindManuscript(string manuscriptName)
        {
            foreach (DocumentGroup manuscriptGroup in this)
            {
                foreach (Document manuscript in manuscriptGroup.Manuscripts)
                {
                    if (manuscript.Name == manuscriptName)
                        return manuscript;
                }

                return manuscriptGroup.Groups.FindManuscript(manuscriptName);
            }

            return null;
        }
    }
}
